package com.heima.search.service.impl;

import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.heima.common.exception.CustomException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;

    /**
     * 保存用户搜索历史记录
     *
     * @param userSearchDto
     */
    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDto userSearchDto) {
        //检查参数
        String searchWords = userSearchDto.getSearchWords();
        Integer entryId = userSearchDto.getEntryId();
        if (userSearchDto == null || StringUtils.isBlank(searchWords) || entryId == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 查询行为实体
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(entryId, userSearchDto.getEquipmentId());
        if (apBehaviorEntry == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体不存在");
        }
        //3 查询当前用户搜索的关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(entryId).and("keyword").is(searchWords))
                , ApUserSearch.class);
        //3.1 存在则更新最新时间，更新状态
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        } else {
            //3.2 不存在则新增
            apUserSearch = new ApUserSearch();
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setEntryId(entryId);
            apUserSearch.setKeyword(searchWords);
            mongoTemplate.save(apUserSearch);
        }
    }

    /**
     * 加载用户搜索历史记录  显示10条
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto dto) {
        //检查参数
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        int size = 0;
        if (dto.getPageSize() == 0) {
            size = 10;
        }
        ArrayList<ApUserSearch> apUserSearcheList = new ArrayList<>();
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            Integer entryId = user.getId();
            //查询实体
            ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(entryId, dto.getEquipmentId());
            // 查询当前用户的搜索列表  按照时间倒序
            if (apBehaviorEntry != null) {
                List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("entryId").is(entryId))
                                .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(size)
                        , ApUserSearch.class);
                return ResponseResult.okResult(apUserSearches);
            }
        }
        return ResponseResult.okResult(apUserSearcheList);
    }

    /**
     * 删除用户搜索历史记录
     *
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        //1.检查参数
        if (historySearchDto == null || historySearchDto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.检查登录状态
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 删除
      mongoTemplate.remove(Query.query(Criteria.where("entryId").is(user.getId()).and("id")
              .is(historySearchDto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
